package com.dews.information.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dews.common.core.domain.model.LoginUser;
import com.dews.common.exception.ServiceException;
import com.dews.common.utils.SecurityUtils;
import com.dews.information.convert.ClazzInfoConvert;
import com.dews.information.domain.dto.ClazzInfoDTO;
import com.dews.information.domain.dto.ClazzInfoQueryDTO;
import com.dews.information.domain.entity.ClazzInfo;
import com.dews.information.domain.entity.Subject;
import com.dews.information.domain.vo.ClazzInfoVo;
import com.dews.information.mapper.ClazzInfoMapper;
import com.dews.information.mapper.SubjectMapper;
import com.dews.information.service.IClazzInfoService;
import com.dews.system.domain.SysDept;
import com.dews.system.mapper.SysDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 班级信息Service业务层处理
 *
 * @author qingfeng
 * @date 2025-01-14
 */
@Service
public class ClazzInfoServiceImpl extends ServiceImpl<ClazzInfoMapper, ClazzInfo> implements IClazzInfoService {

    private ClazzInfoMapper clazzInfoMapper;
    private SysDeptMapper sysDeptMapper;
    private SubjectMapper subjectMapper;

    @Autowired
    public ClazzInfoServiceImpl(ClazzInfoMapper clazzInfoMapper,
                                SysDeptMapper sysDeptMapper,
                                SubjectMapper subjectMapper) {
        this.clazzInfoMapper = clazzInfoMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.subjectMapper = subjectMapper;
    }

    /**
     * 查询班级信息列表
     *
     * @param clazzInfoQueryDTO
     * @return 班级信息
     */
    @Override
    public List<ClazzInfoVo> selectClazzInfoList(ClazzInfoQueryDTO clazzInfoQueryDTO) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (ObjectUtil.isEmpty(loginUser)) {
            throw new ServiceException("当前用户不支持查询班级信息！");
        }
        LambdaQueryWrapper<ClazzInfo> queryWrapper = Wrappers.lambdaQuery(ClazzInfo.class)
                .like(StrUtil.isNotBlank(clazzInfoQueryDTO.getClazzName()), ClazzInfo::getClazzName, clazzInfoQueryDTO.getClazzName())
                .eq(StrUtil.isNotBlank(clazzInfoQueryDTO.getGrade()), ClazzInfo::getGrade, clazzInfoQueryDTO.getGrade())
                .eq(ObjectUtil.isNotNull(clazzInfoQueryDTO.getEducationalSystem()), ClazzInfo::getEducationalSystem, clazzInfoQueryDTO.getEducationalSystem())
                .eq(StrUtil.isNotBlank(clazzInfoQueryDTO.getClazzType()), ClazzInfo::getClazzType, clazzInfoQueryDTO.getClazzType());
        // 判断当前用户是否是专业负责人  TODO 后面可把专业角色封装成枚举值
        if (loginUser.getUser().getRoles().stream().anyMatch(e -> e.getRoleKey().equals("subject"))) {
            // 查询专业ID
            Subject subject = subjectMapper.selectOne(
                    Wrappers.lambdaQuery(Subject.class)
                            .eq(Subject::getDirectorId, loginUser.getUserId())
            );
            queryWrapper.eq(ClazzInfo::getSubjectId, subject.getId());
            queryWrapper.eq(ClazzInfo::getDepId, loginUser.getDeptId());
        }
        List<ClazzInfo> clazzInfoList = baseMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(clazzInfoList)) {
            return Collections.emptyList();
        }
        Map<Long, String> depMap = sysDeptMapper.selectList(
                        Wrappers.lambdaQuery(SysDept.class)
                                .in(SysDept::getDeptId, clazzInfoList.stream().map(ClazzInfo::getDepId).collect(Collectors.toSet()))
                ).stream()
                .collect(Collectors.toMap(
                        SysDept::getDeptId,
                        SysDept::getDeptName
                ));
        Map<Integer, String> subjectMap = subjectMapper.selectList(
                        Wrappers.lambdaQuery(Subject.class)
                                .in(Subject::getId, clazzInfoList.stream().map(ClazzInfo::getSubjectId).collect(Collectors.toSet()))
                ).stream()
                .collect(Collectors.toMap(
                        Subject::getId,
                        Subject::getSubjectName
                ));

        List<ClazzInfoVo> clazzInfoVoList = ClazzInfoConvert.INSTANCE.convert(clazzInfoList);
        clazzInfoVoList.forEach(e -> {
            e.setDepName(depMap.getOrDefault(e.getDepId(), ""));
            e.setSubjectName(subjectMap.getOrDefault(e.getSubjectId(), ""));
        });
        return clazzInfoVoList;
    }

    /**
     * 查询班级信息
     *
     * @param id 班级信息主键
     * @return 班级信息
     */
    @Override
    public ClazzInfoVo selectClazzInfoById(Integer id) {
        ClazzInfo clazzInfo = clazzInfoMapper.selectById(id);
        ClazzInfoVo clazzInfoVo = ClazzInfoConvert.INSTANCE.convert(clazzInfo);
        // 获取学院名称
        clazzInfoVo.setDepName(sysDeptMapper.selectById(clazzInfoVo.getDepId()).getDeptName());
        // 获取专业名称
        clazzInfoVo.setSubjectName(subjectMapper.selectById(clazzInfoVo.getSubjectId()).getSubjectName());
        return clazzInfoVo;

    }

    /**
     * 新增班级信息
     *
     * @param clazzInfoDTO
     * @return 结果
     */
    @Override
    public int insertClazzInfo(ClazzInfoDTO clazzInfoDTO) {
        ClazzInfo clazzInfo = ClazzInfoConvert.INSTANCE.convert(clazzInfoDTO);
        checkClazzInfo(clazzInfo);
        return clazzInfoMapper.insert(clazzInfo);

    }

    /**
     * 修改班级信息
     *
     * @param clazzInfoDTO
     * @return 结果
     */
    @Override
    public int updateClazzInfo(ClazzInfoDTO clazzInfoDTO) {
        ClazzInfo clazzInfo = ClazzInfoConvert.INSTANCE.convert(clazzInfoDTO);
        checkClazzInfo(clazzInfo);
        return clazzInfoMapper.updateById(clazzInfo);
    }

    private void checkClazzInfo(ClazzInfo clazzInfo) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (ObjectUtil.isEmpty(loginUser)) {
            throw new ServiceException("当前用户不支持修改班级信息！");
        }
        clazzInfo.setDepId(loginUser.getDeptId());
        Long count = clazzInfoMapper.selectCount(
                Wrappers.lambdaQuery(ClazzInfo.class)
                        .eq(ClazzInfo::getDepId, loginUser.getDeptId())
                        .eq(ClazzInfo::getSubjectId, clazzInfo.getSubjectId())
                        .eq(ClazzInfo::getGrade, clazzInfo.getGrade())
                        .eq(ClazzInfo::getEducationalSystem, clazzInfo.getEducationalSystem())
                        .eq(ClazzInfo::getClazzType, clazzInfo.getClazzType())
                        .ne(ObjectUtil.isNotEmpty(clazzInfo.getId()), ClazzInfo::getId, clazzInfo.getId())
                        .and(wrapper ->
                                wrapper.eq(ClazzInfo::getClazzName, clazzInfo.getClazzName())
                                        .or()
                                        .eq(ClazzInfo::getClazzCode, clazzInfo.getClazzCode())
                        )
        );

        if (count > 0) {
            throw new ServiceException("方案中课程名称或课程代码已存在，请勿重复添加");
        }
    }

    /**
     * 批量删除班级信息
     *
     * @param ids 需要删除的班级信息主键
     * @return 结果
     */
    @Override
    public int deleteClazzInfoByIds(List<Integer> ids) {
        return clazzInfoMapper.deleteBatchIds(ids);
    }

    /**
     * 根据当前年份生成上下五年之间的所有年级集合
     * @return
     */
    @Override
    public List<String> getGradeList() {
        // 根据当前年份生成上下五年之间的所有年级集合，使用整型流
        return IntStream.range(0, 10)
                .mapToObj(i -> LocalDate.now().getYear() - 5 + i + "级")
                .collect(Collectors.toList());
    }


}
